package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{
    private final StringRedisTemplate stringRedisTemplate;
    private final String name;
    public SimpleRedisLock(String name,StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }


    private final static String key_prefix = "lock:";
    private final static String id_prefix = UUID.randomUUID().toString(true);
    private final static DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    // timeoutSec为业务的执行时间，因为获取到这个锁之后过了时间锁就过期了
    @Override
    public boolean tryLock(Long timeoutSec) {
        String currentId = id_prefix + Thread.currentThread().getId();
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key_prefix + name, currentId, timeoutSec, TimeUnit.SECONDS);
        // 防止拆箱过程中出现空指针异常
        return Boolean.TRUE.equals(b);

    }

    @Override
    public void unlock() {
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(key_prefix + name),
                id_prefix + Thread.currentThread().getId());
    }

//    @Override
//    public void unlock() {
//        String threadId = id_prefix + Thread.currentThread().getId();
//        String id = stringRedisTemplate.opsForValue().get(key_prefix + name);
//        if (threadId.equals(id)){
//            stringRedisTemplate.delete(key_prefix + name);
//        }
//    }
}
